package handler;

import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import constant.Constant;
import lombok.Data;
import org.apache.poi.common.usermodel.HyperlinkType;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import util.ExcelStyleUtil;

@Data
public class TableSheetAfterHandler implements SheetWriteHandler {

    private String tableName;

    private String tableCode;

    public TableSheetAfterHandler(String tableName, String tableCode) {
        this.tableName = tableName;
        this.tableCode = tableCode;
    }

    /**
     * 第一行合并前三个单元格，添加表名
     * 第一行第四个单元格设置返回目录链接
     */
    @Override
    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        Sheet sheet = writeSheetHolder.getSheet();

        // 合并第一行前三列
        Row row0 = sheet.createRow(0);
        Cell cell00 = row0.createCell(0);

        cell00.setCellStyle(ExcelStyleUtil.tableHeaderStyle(writeWorkbookHolder.getWorkbook()));
        cell00.setCellValue(tableName + "(" + tableCode + ")");
        CellRangeAddress mergeRegion = new CellRangeAddress(0, 0, 0, 2);
        sheet.addMergedRegion(mergeRegion);

        // 在后面单元格添加返回目录
        Cell cell03 = row0.createCell(3);
        cell03.setCellValue(Constant.RETURN_INDEX);
        CreationHelper helper = writeSheetHolder.getSheet().getWorkbook().getCreationHelper();
        // 设置本文档内sheet链接，需要类型为HyperlinkType.DOCUMENT
        Hyperlink hyperlink = helper.createHyperlink(HyperlinkType.DOCUMENT);
        // #sheet名!A1   #：表示本文档 sheet名：sheet的名称 !A1：链接到该sheetA1单元格
        hyperlink.setAddress("#" + Constant.INDEX + "!A1");
        cell03.setHyperlink(hyperlink);

    }
}
